//#define __DEBUG__
// by Xeno
#define THIS_FILE "fn_makemgroup.sqf"
#include "x_setup.sqf"

__TRACE_1("_this","_this");

private ["_pos", "_unitliste", "_grp", "_ret", "_do_points"];
PARAMS_3(_pos,_unitliste,_grp);
_do_points = (count _this > 3);_ret = [];
{
	_one_unit = _grp createunit [_x, _pos, [], 10,"NONE"];
	_one_unit call FUNC(removeNVGoggles);
	_one_unit call FUNC(removefak);
	_one_unit call FUNC(removetech);
	_one_unit call FUNC(addInsignia);
	_svec = sizeOf _x;
	_isFlat = (position _one_unit) isFlatEmpty [_svec / 2, 150, 0.7, _svec, 0, false, _one_unit];
	if (count _isFlat > 1) then {
		_isFlat set [2,0];
		if (_one_unit distance _isFlat < 50) then {
			_one_unit setPos _isFlat;
		};
	};
	_one_unit setVariable ["BIS_noCoreConversations", true];
	if (GVAR(domdatabase)) then {
		[_one_unit, {_this addEventHandler ["killed", {if (isPlayer (_this select 1)) then {[QGVAR(PAIKP), _this select 1] call FUNC(NetCallEventCTS)}}];}] call FUNC(setUnitCode);
	};
	#ifdef __TT__
	if (_do_points) then {
		[_one_unit, {_this addMPEventHandler ["MPkilled", {if (isServer) then {[[15, 3, 2, 1],_this select 1, _this select 0] call FUNC(AddKills);(_this select 0) removeAllMPEventHandlers "MPKilled"}}]}] call FUNC(setUnitCode);
	};
	#endif
	if (GVAR(with_ai) && {GVAR(with_ranked)}) then {
		[_one_unit, {_this addEventHandler ["killed", {if (!isPlayer (_this select 1)) then {[QGVAR(AddKillAI), [1,_this select 1]] call FUNC(NetCallEventCTS)}}]}] call FUNC(setUnitCode);
	};
	// TYRGHEN - Added the ability to use an external AI Skill setter (Zeus AI ServerSkill)
	if (GVAR(with_external_ai_skill) == 1) then {
		_one_unit setUnitAbility ((GVAR(skill_array) select 0) + (random (GVAR(skill_array) select 1)));
	};
	// TYRGHEN - Adds some built in scripted event handlers to units to make them more reactive
	if (!(isNil QGVAR(with_aihandlers)) && {GVAR(with_aihandlers) == 0}) then {
		_one_unit call FUNC(scriptedreactions);
	};
	_ret set [count _ret, _one_unit];
	// does not subtract if a unit dies!
	#ifdef __GROUPDEBUG__
	if (side _grp == GVAR(side_enemy)) then {
		__INC(GVAR(infunitswithoutleader));
	};
	#endif
} foreach _unitliste;
#ifdef __GROUPDEBUG__
if (side _grp == GVAR(side_enemy)) then {
	__DEC(GVAR(infunitswithoutleader));
};
#endif
(leader _grp) setRank "SERGEANT";
[_grp, 1] call FUNC(setGState);
_ret